package com.zyl.pagergalleryloadmoredemo.viewModel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.zyl.pagergalleryloadmoredemo.pojo.PhotoItem
import com.zyl.pagergalleryloadmoredemo.pojo.Pixabay
import com.zyl.pagergalleryloadmoredemo.volley.VolleyUtils
import kotlin.math.ceil

const val DATA_STATUS_CAN_LOAD_MORE = 0  //还可以加载
const val DATA_STATUS_NO_MORE = 1 //数据加载完毕
const val DATA_STATUS_NETWORK_ERROR = 2 //网络出现错误

class GalleryViewModel(application: Application) : AndroidViewModel(application) {

    private val _dataStatusLive = MutableLiveData<Int>() //存储加载状态
    val dataStatusLive get() = _dataStatusLive

    private val _photoLiveData: MutableLiveData<List<PhotoItem>> = MutableLiveData()
    val photoLiveData: LiveData<List<PhotoItem>>
        get() = _photoLiveData

    var needToScrollToTop = true //回到顶部
    private val perPage = 100 //每一页加载多少
    private val keyWords = arrayOf("happy", "Chines", "USA", "UK","flowers","animals")

    private var currentPage = 1 //当前页码
    private var totalPage = 1 //总页数
    private var currentKey = "cat" //当前的关键词
    private var isNewQuery = true //是否是新请求
    private var isLoading = false //是否还可以加载

    init {
        resetQuery()
    }

    fun resetQuery() {
        //重新加载就要重新把数据初始化
        currentPage = 1
        totalPage = 1
        currentKey = keyWords.random()
        isNewQuery = true
        needToScrollToTop = true
        fetchData()
    }

    fun fetchData() {
        if (isLoading) return //不可以在加载了
        if (currentPage > totalPage) { //数据加载完毕了
            _dataStatusLive.value = DATA_STATUS_NO_MORE
            return
        }
        isLoading = true

        val stringRequest: StringRequest = StringRequest(
            Request.Method.GET,
            getUrl(),
            {
                with(Gson().fromJson(it, Pixabay::class.java)) {
                    totalPage = ceil(totalHits.toDouble() / perPage).toInt() //将总共图片数/每页的数 = 总页数
                    if (isNewQuery) {//是否是重新加载
                        //直接将请求的给 _photoLiveData
                        _photoLiveData.value = hits.toList()
                    } else {
                        //不是重新加载,那么要加上前面的数据
                        //将二个数组合并
                        _photoLiveData.value =
                            arrayListOf(_photoLiveData.value!!, hits.toList()).flatten()

                    }
                }
                _dataStatusLive.value = DATA_STATUS_CAN_LOAD_MORE //还可以加载数据
                isLoading = false //可以加载
                isNewQuery = false //不是重新加载
                currentPage++ //请求页数 +1

//                _photoLiveData.value = Gson().fromJson(it, Pixabay::class.java).hits.toList()
            },
            {
                _dataStatusLive.value = DATA_STATUS_NETWORK_ERROR //网络错误
                isLoading = false
                Log.d("myTAG", "fetchData: json加载失败")
            }
        )

        VolleyUtils.getVolleyUtils(getApplication()).getRequest.add(stringRequest)


    }

    fun getUrl(): String {
        return "https://pixabay.com/api/?key=20367884-4ff0b66c3d8b80b87f646de62&q=${currentKey}&per_page=${perPage}&page=${currentPage}"
    }

}